import React, { useEffect } from 'react';
import createContext from 'zustand/context';

import { useAuth, useAuthStore } from '~/modules/auth/store/use-auth';
import { useTokenStore } from '~/modules/auth/store/use-token';

const { Provider } = createContext();

export interface Props {
  children?: React.ReactNode | React.ReactNode[];
}

export const AuthAware = ({ children }: Props) => {
  if (
    // @ts-ignore
    !useTokenStore.persist.hasHydrated() ||
    // @ts-ignore
    !useAuthStore.persist.hasHydrated()
  ) {
    return null;
  }
  const { reload } = useAuth();
  useEffect(() => {
    reload();
  }, []);
  return <Provider createStore={() => useTokenStore}>{children}</Provider>;
};
